package com.xlh.support.training.service.impl;

import com.xlh.enums.FileTypeEnum;
import com.xlh.enums.LocalResourcesEnum;
import com.xlh.exception.common.GlobalException;
import com.xlh.service.MdHtmlFileService;
import com.xlh.support.training.dao.helper.TrainingMapperHelper;
import com.xlh.support.training.po.TrainingManualSavePO;
import com.xlh.support.training.service.TrainingManualService;
import com.xlh.support.training.vo.TrainingManualVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author cheer
 */
@Service
@Slf4j
public class TrainingManualServiceImpl implements TrainingManualService {

    @Autowired
    private MdHtmlFileService mdHtmlFileService;

    @Autowired
    private TrainingMapperHelper trainingMapperHelper;


    @Override
    public TrainingManualVO getTrainingManual(Long trainingId) {
        if (trainingMapperHelper.getById(trainingId) == null) {
            throw new GlobalException("实训不存在");
        }
        return TrainingManualVO.builder()
                .conTent(mdHtmlFileService.readFile(LocalResourcesEnum.TRAINING.getLocalUploadPath(),
                        trainingId + ".md"))
                .htmlContent(mdHtmlFileService.readFile(LocalResourcesEnum.TRAINING.getLocalUploadPath(),
                        trainingId + ".html"))
                .build();
    }

    @Override
    public String getTrainingManualMd(Long trainingId) {
        if (trainingMapperHelper.getById(trainingId) == null) {
            throw new GlobalException("实训不存在");
        }
        return mdHtmlFileService.readFile(LocalResourcesEnum.TRAINING.getLocalUploadPath(),
                StringUtils.join(trainingId, FileTypeEnum.MARKDOWN.getExtension()));
    }

    @Override
    public void saveTrainingManual(Long trainingId, TrainingManualSavePO trainingManualSavePO) {
        mdHtmlFileService.writeAllFile(trainingManualSavePO.getContent(), trainingManualSavePO.getHtmlContent(),
                LocalResourcesEnum.TRAINING.getLocalUploadPath(), String.valueOf(trainingId));
    }
}
